package com.corecmd.tcloud.tcimserver.im.handler;

import com.corecmd.tcloud.tcimcommon.im.domain.MessageRequestPacket;
import com.corecmd.tcloud.tcimserver.im.common.ImSessionHolder;
import com.corecmd.tcloud.tcimserver.service.SendMessageToClientsService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/20
 * @description :
 **/
@Slf4j
@Scope("prototype")
@Component
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Autowired
    private SendMessageToClientsService sendMessageToClientsService;
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageRequestPacket messageRequestPacket) throws Exception {
        log.info("服务端收到消息请求");
        String receiverId = messageRequestPacket.getReceiverId();
        NioSocketChannel channel = ImSessionHolder.SESSIONHOLDERS.get(receiverId);
        if (channel != null){
            //转发消息
            sendMessageToClientsService.sendMessage(messageRequestPacket);
        } else {
            log.info("服务端收到消息，但是找不到用户：{}"+receiverId+"的连接信息");
        }
        channelHandlerContext.flush();
    }
}
